<%--
  Created by IntelliJ IDEA.
  User: 27716
  Date: 2024/10/30
  Time: 20:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加（一对多的数据组装）</title>
  <script src="../../static/js/jquery-1.8.2.min.js"></script>
  <link rel="stylesheet" href="../../static/css/css.css">
    <script>
        //文档就绪函数
        $(function (){
            $("#purchaseCode").html(getPurchaseCode());
            getSupplier();
        })
        function getPurchaseCode(){
            //单号 规则：JH + 日期 + 随机数
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth()+1;
            let day = date.getDate();
            //补0操作
            month = month<10?"0"+month:month;
            day = day<10?"0"+day:day;
            //随机数
            let number = Math.floor(Math.random()*9999-1000+1)+1000;
            //组合
            return "JH"+year+month+day+number;
        }
        //获取动态下拉框
        function getSupplier(){
            $.ajax({
                url:"/supplier/getSupplier",
                dataType:"json",
                success(res){
                    console.log(res);
                    for (let o of res) {
                        $("#supplierId").append(`
                            <option value="\${o.supplierId}" data-aa=\${o.address}>\${o.supplierName}</option>
                        `)
                    }
                },
                error(){
                    alert("宝宝出现问题了")
                }
            })
        }
    </script>
</head>
<body>
<table>
  <tr>
      <td>单号</td>
      <td>
          <span id="purchaseCode"></span>
      </td>
      <td>供应商</td>
      <td>
          <select id="supplierId" onchange="getAddress()">
              <option value="">请选择</option>
          </select>
      </td>
      <td>应付金额</td>
      <td>
          <span id="purchaseSumPrice"></span>
      </td>
  </tr>
  <tr>
      <td>实付金额</td>
      <td>
          <span id="payMoney"></span>
      </td>
      <td>购物日期</td>
      <td>
            <input type="datetime-local" step="1" id="purchaseTime">
      </td>
      <td>备注（购物地址）</td>
      <td>
            <textarea id="address" ></textarea>
      </td>
  </tr>
  <tr>
    <td>折扣</td>
    <td>
        <select id="discount" onchange="getPayMoney()">
          <option value="1">无折扣</option>
          <option value="0.9">九折</option>
          <option value="0.8">八折</option>
          <option value="0.85">八五折</option>
          <option value="0.5">五折</option>
        </select>
    </td>
    <td>下单人</td>
      <input type="hidden" id="uid" value="${user.uid}">
    <td>
        ${user.username}
    </td>
      <td>购买总数 <span id="purchaseNum"></span> </td>
      <td colspan="100">
          <input type="button" value="选择商品" onclick="findBySupplierId()">
      </td>
  </tr>
</table>
<%--table 展示 查询到的 商品信息--%>
<table id="table">
    <tr>
        <td>商品编号id</td>
        <td>商品编码</td>
        <td>商品名称</td>
        <td>库存数量</td>
        <td>采购价格</td>
    </tr>
</table>
</body>
<script>
    //选择商品按钮
    function findBySupplierId(){
        //1.获取供应商的id
        let supplierId = $("#supplierId").val();
        //2.非空校验
        if(!supplierId){
            alert("请先选择供应商");
            return;
        }
        //3.组装对象
        let obj = {supplierId}
        //4.ajax异步请求
        $.ajax({
            url:"/goods/findGoodsBySupplierId",
            type:"post",
            data:{reqInfos:JSON.stringify(obj)},
            dataType: "json",
            success(res) {
                console.log(res);
                $("#table").empty();
                $("#table").append(`
                    <tr>
                        <td>
                            <input type="checkbox" id="check" onchange="getMoney()">
                        </td>
                        <td>商品编号id</td>
                        <td>商品编码</td>
                        <td>商品名称</td>
                        <td>库存数量</td>
                        <td>采购价格</td>
                        <td>采购数量</td>
                        <td>采购总金额</td>
                    </tr>
                `)
                for (let o of res) {
                    $("#table").append(`
                        <tr>
                            <td>
                                <input type="checkbox" class="ck" value="\${o.goodsId}" onchange="getMoney()">
                            </td>
                            <td>\${o.goodsId}</td>
                            <td>\${o.goodsCode}</td>
                            <td>\${o.goodsName}</td>
                            <td>\${o.inventoryQuantity}</td>
                            <td>\${o.purchasingPrice}</td>
                            <td>
<!--采购数量-->
                                <input type="text" id="num\${o.goodsId}" onchange="getSumPrice(\${o.purchasingPrice},this,\${o.goodsId})">
                            </td>
                            <td>
<!--总金额-->
                                <span id="sumPrice\${o.goodsId}">0</span>
                            </td>
                        </tr>
                    `)
                }
            //循环结束之后追加按钮
                $("#table").append(`
                        <tr>
                            <td colspan="100">
                                <input type="button" value="确定进货入库" onclick="addPurchase()">
                                <input type="button" value="返回" onclick="history.back()">
                            </td>
                        </tr>
                    `)
            },
            error() {
                alert("宝宝，服务器错误了")
            }
        })
    }
    $(document).on("click","#check",function (){
        $(".ck").prop("checked",this.checked);
    })
    //计算购买的总价格
    function getSumPrice(price,num,goodsId){
        //获取this的值
        let n = $(num).val();
        if(n<=0){
            alert("一个不买想白嫖？？");
            $(num).val(null);
            return;
        }
        //保留小数后几位
        $("#sumPrice"+goodsId).html((price * n).toFixed(2))
    }

    //计算 应付金额
    function getMoney(){
        let sum = 0.0;
        let count =0;
        //获取选中的复选框
        $(".ck:checked").each(function (){
            //获取 复选框的值 （商品id）
            let goodsId = $(this).val();
            //金额已经动态绑定商品ID，更怒商品ID获取对应的金额
            let sumPrice = $("#sumPrice"+goodsId).html();

            //获取数量（input）
            let num = $("#num"+goodsId).val();
            count+= +num;
            //累积求和
            sum += +sumPrice;//+ 作用 字符串转数字
        })
        //赋值
        $("#purchaseSumPrice").html(sum);
        //实付金额默认原价 （应付金额）
        $("#payMoney").html(sum);
        //总数
        $("#purchaseNum").html(count);
    }
    //只计算折扣价  静态下拉框改变事件
    function getPayMoney(){
        //获取 折扣 获取下拉框的值
        let discount = $("#discount").val();
        // 应付金额 
        let purchaseSumPrice = $("#purchaseSumPrice").html();
        //实付金额
        $("#payMoney").html((purchaseSumPrice * discount).toFixed(2));

    }

    //添加
    function addPurchase(){
        //取值 （一个进货单对应 多个商品明细表 （中间表））
        let purchaseCode = $("#purchaseCode").html()
        let supplierId = $("#supplierId").val()
        let purchaseSumPrice = $("#purchaseSumPrice").html()
        let payMoney = $("#payMoney").html()
        let purchaseTime = $("#purchaseTime").val()
        let address = $("#address").val()
        let discount = $("#discount").val()
        let uid = $("#uid").val()
        let purchaseNum = $("#purchaseNum").html()

        //获取 中间表 --> 只需要获取商品ID
        //获取选中的复选框
        let arr = [];
        $(".ck:checked").each(function (){
            let goodsId = $(this).val();
            let num = $("#num"+goodsId).val();
            //购买金额 span
            let money = $("#sumPrice"+goodsId).html();
            //组装中间表对象
            let obj = {goodsId,num,money};
            arr.push(obj);
            ///非空校验
            if(!purchaseCode||!supplierId||!purchaseSumPrice||!payMoney||!purchaseTime||!address||!discount||!uid){
                alert("数据不能为空");
                return
            }
            if(!arr.length){
                alert("请先选择要 购买的商品");
                return;
            }
        })
        //一对多的数据组装 （难点）
        let obj = {
            purchaseCode,
            supplierId,
            purchaseSumPrice,
            payMoney,
            purchaseTime,
            address,
            discount,
            uid,
            purchaseNum,
            arr
        }
        $.ajax({
            url:"/purchase/addPurchase",
            type: "post",
            data:{reqInfos:JSON.stringify(obj)},
            dataType:"json",
            success(res){
                console.log(res);
                if(res === 200){
                    alert("添加成功");
                    location.href = "list.jsp";
                }
            },
            error(){
                alert("服务器故障")
            }
        })
    }
    //下拉框 动态绑定地址
    function getAddress(){
        let data = $("#supplierId option:selected").data("aa");
        $("#address").html(data);
    }
</script>
</html>
